<script setup lang="ts">
import { Ref, computed, onMounted, ref, toValue, unref } from 'vue'
import { Search, CirclePlus, Plus } from '@element-plus/icons-vue';
import { Refresh } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { UploadProps } from 'element-plus'
import {
  reqFindSupermarket,
  reqaddSupermarket,
  reqfindSupermarketById,
  reqModifySupermarket,
  reqRemoveSupermarket
} from '@/api/scholl';
import { ReqFindSchoolParams, AddParams } from './types';
import { reqUploadPic } from '@/api/message';
import { useStore } from '@/pinna';
import { useRoute } from 'vue-router';
const infoStore = useStore()
onMounted(() => {
  findData()
})

// 搜索栏
const pageNo: Ref<number> = ref(1)
const pageSize = ref(10)
const searchFrom: Ref<ReqFindSchoolParams> = ref({
  schoolName: '',
  schoolAddress: '',
  schoolClassify: ''
})

const reset = () => {
  searchFrom.value = {
    schoolName: '',
    schoolAddress: '',
    schoolClassify: ''
  }
  findData()
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  findData()
}

const handleCurrentChange = (val: number) => {
  pageNo.value = val
  findData()
}

const total: Ref<number> = ref(0)
const tableData: Ref<Partial<AddParams[]>> = ref([])

const findData = async () => {
  await reqFindSupermarket({
    pageNo: toValue(pageNo),
    pageSize: toValue(pageSize),
    ...unref(searchFrom)
  }).then((res: any) => {
    const { code, data, total: tableTotal } = res

    if (code === 200) {
      tableData.value = data
      total.value = tableTotal

    } else {
      ElMessage({
        message: '请求异常',
        type: 'warning'
      })
    }
  })
}

// 添加社区资讯弹窗
let dialogHost = ref(false)
let dialogHostTitle = ref('添加')
const formLabelWidth = '100px'
const addHsotForm: Ref<AddParams> = ref({
  id: "",
  schoolName: "",
  schoolAddress: "",
  schoolClassify: "",
  schoolPhone: "",
  schoolPic: [],
  studentNum: 0
})

const resetDialogHostFrom = () => {
  fileList.value = []
  addHsotForm.value = {
    id: "",
    schoolName: "",
    schoolAddress: "",
    schoolClassify: "",
    schoolPhone: "",
    schoolPic: [],
    studentNum: 0
  }
}

const addHostDialog = () => {
  resetDialogHostFrom()
  dialogHostTitle.value = '添加'
  dialogHost.value = true
}

const addHostSubmit = async () => {
  if (dialogHostTitle.value == '添加') {
    await reqaddSupermarket(unref(addHsotForm)).then((res: any) => {
      const { code } = res

      if (code === 200) {
        dialogHost.value = false
        findData()
        ElMessage({
          message: '添加成功',
          type: 'success'
        })

      } else {
        const message = res.msg || '请求异常'
        ElMessage({
          message: message,
          type: 'warning'
        })
      }
    })
  } else if (dialogHostTitle.value == '修改') {
    await reqModifySupermarket({ ...unref(addHsotForm), id: unref(editId) }).then((res: any) => {
      if (res.code === 200) {
        dialogHost.value = false
        findData()
        ElMessage({
          message: '修改信息成功',
          type: 'success'
        })

      } else {
        const message = res.msg || '请求异常'
        ElMessage({
          message: message,
          type: 'warning'
        })
      }
    })

  }

}

let editId = ref('')
const updateHostDialog = async (id: string) => {
  resetDialogHostFrom()
  dialogHostTitle.value = '修改'
  dialogHost.value = true
  editId.value = id
  findRoleInfo(id, 'edit')
}

const deleteHostDialog = async (id: string) => {
  ElMessageBox.confirm(
    '是否确认删除?',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      await reqRemoveSupermarket({ id }).then((res: any) => {
        if (res.code === 200) {
          ElMessage({
            message: '删除成功',
            type: 'success'
          })
          findData()
        } else {
          ElMessage({
            message: '请求异常',
            type: 'warning'
          })
        }
      })
    })

}

const findRoleInfo = async (id: string, type?: 'edit' | 'add') => {
  resetDialogHostFrom()
  dialogHostTitle.value = type === 'edit' ? '修改' : '查看'
  dialogHost.value = true
  await reqfindSupermarketById({
    id
  }).then((res: any) => {
    const { code, data } = res

    if (code === 200) {
      addHsotForm.value = data
      fileList.value = data.schoolPic.length > 0 ?
        (data.schoolPic as string[]).map(t => {
          return {
            name: 'test.jpeg',
            url: t
          }
        }) : []

    } else {
      ElMessage({
        message: '请求异常',
        type: 'warning'
      })
    }
  })
}

let fileList = ref<any[]>([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const updataImg = async (data: any) => {
  await reqUploadPic({ image: data.file }).then((res: any) => {
    addHsotForm.value.schoolPic?.push(res.data)
  })
}

const handleRemove: UploadProps['onRemove'] = (uploadFile) => {
  const index = addHsotForm.value.schoolPic?.findIndex(t => t == uploadFile.url)
  toValue(addHsotForm).schoolPic.splice(index, 1)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
const isReadonlyHandler = computed(() => {
  return dialogHostTitle.value !== '查看'
})
const route = useRoute();
const isRouterUser = computed(() => {
  return route.path.includes('reception')
})
</script>

<template>
  <el-card>
    <template v-if="!isRouterUser" #header>
      <div class="card-header">
        <span><strong>{{ infoStore.$state.info.role == 'admin' ? '学校管理' : '学校查看' }}</strong></span>
      </div>

    </template>
    <div class="query-input">
      <el-input v-model="searchFrom.schoolName" placeholder="学校名字" />
      <el-input v-model="searchFrom.schoolAddress" placeholder="学校地址" />
      <el-input v-model="searchFrom.schoolClassify" placeholder="学校类别" />
      <el-button type="primary" @click="findData()">
        <el-icon>
          <Search />
        </el-icon>
        查询
      </el-button>
      <el-button type="danger" @click="reset()">
        <el-icon>
          <Refresh />
        </el-icon>
        重置
      </el-button>
    </div>

  </el-card>
  <div class="card-layout" v-if="isRouterUser">
    <el-card v-for="(row) in tableData" @click="findRoleInfo((row!.id) as any)"
      style="max-width: 480px;width: 32%;height: 340px;">
      <template #header>
        <div class="card-header">
          <span>{{ row?.schoolName }}</span>
        </div>
      </template>
      <div style="height:150px">
        <p class="text item">{{ '学校地址: ' + row?.schoolAddress }}</p>
        <p class="text item">{{ '学校分类: ' + row?.schoolClassify }}</p>
        <p class="text item">{{ '学生数量: ' + row?.studentNum }}</p>
      </div>

      <template #footer>
        <p style="color: blue;font-size: 12px;float: right;">{{ '学校联系方式: ' + (row?.schoolPhone || '暂无') }}</p>
      </template>
    </el-card>
  </div>
  <el-card v-else>
    <div>
      <el-button v-if="infoStore.$state.info.role == 'admin'" key="'添加学校'" @click="addHostDialog()" :icon="CirclePlus"
        type="primary" text bg class="addUser">添加学校</el-button>
    </div>
    <el-table :data="tableData" stripe style="width: 100%">
      <el-table-column prop="schoolName" label="学校名字" />
      <el-table-column prop="schoolAddress" label="学校地址" />
      <el-table-column prop="schoolClassify" label="学校分类" />
      <el-table-column prop="schoolPhone" label="学校联系方式">
      </el-table-column>
      <el-table-column prop="studentNum" label="学生数量" />
      <el-table-column fixed="right" label="操作">
        <template #default="scope">
          <el-space wrap>
            <el-button type="primary" size="small" plain @click="findRoleInfo(scope.row.id)">查看</el-button>
            <el-button v-if="infoStore.$state.info.role == 'admin'" type="primary" size="small" plain
              @click="updateHostDialog(scope.row.id)">编辑</el-button>
            <el-button v-if="infoStore.$state.info.role == 'admin'" type="primary" size="small" plain
              @click="deleteHostDialog(scope.row.id)">删除</el-button>
          </el-space>
        </template>
      </el-table-column>
    </el-table>

    <div class="demo-pagination-block">
      <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
        :background="false" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
  </el-card>
  <!-- 添加户主弹框 -->
  <el-dialog v-model="dialogHost" :title="dialogHostTitle">
    <el-form :model="addHsotForm">
      <el-form-item label="学校名字:" :label-width="formLabelWidth" clearable required>
        <el-input v-model="addHsotForm.schoolName" autocomplete="off" placeholder="请输入学校名字"
          :disabled="!isReadonlyHandler" />
      </el-form-item>
      <el-form-item label="学校地址:" :label-width="formLabelWidth" clearable required>
        <el-input v-model="addHsotForm.schoolAddress" autocomplete="off" placeholder="请输入学校地址"
          :disabled="!isReadonlyHandler" />
      </el-form-item>
      <el-form-item label="学校分类:" :label-width="formLabelWidth" clearable required>
        <el-input v-model="addHsotForm.schoolClassify" autocomplete="off" placeholder="请输入学校分类"
          :disabled="!isReadonlyHandler" />
      </el-form-item>
      <el-form-item label="学校联系方式:" :label-width="formLabelWidth" clearable required>
        <el-input v-model="addHsotForm.schoolPhone" autocomplete="off" placeholder="请输入学校联系方式"
          :disabled="!isReadonlyHandler" />
      </el-form-item>
      <el-form-item label="学校图片:" :label-width="formLabelWidth" clearable required>
        <el-upload v-if="isReadonlyHandler" v-model:file-list="fileList" :http-request="updataImg"
          :headers="{ 'Content-Type': 'multipart/form-data' }" list-type="picture-card"
          :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :disabled="!isReadonlyHandler">
          <el-icon>
            <Plus />
          </el-icon>
        </el-upload>
        <div v-else v-for="fit in fileList" :key="fit" class="block" style="display: flex;flex-wrap: wrap;margin: 8px;">
          <el-image style="width: 250px; height: 250px" :src="fit.url" :fit="'contain'"><template #error>
              <div style="width: 100%;height: 100%;display: flex;align-items: center;">
                无图片
              </div>
            </template></el-image>
        </div>
        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="学生数量:" :label-width="formLabelWidth" clearable required>
        <el-input v-model="addHsotForm.studentNum" autocomplete="off" placeholder="请输入学生数量"
          :disabled="!isReadonlyHandler" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogHost = false">取消</el-button>
        <el-button v-if="isReadonlyHandler" type="primary" @click="addHostSubmit()">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.el-input {
  margin-right: 5px;
  width: 400px;
}

.query-input {
  display: flex;
  gap: 10;
}

.el-card {
  margin-bottom: 10px;
}

.demo-pagination-block {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.addUser {
  float: right;
  margin-right: 10px;
}

.el-button--text {
  margin-right: 15px;
}

.el-select {
  width: 300px;
}

/* 
.el-input & .el-textarea  {
  width: 300px;
} */
.el-textarea {
  width: 400px;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}

.card-layout {
  cursor: pointer;
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  align-items: flex-start;
  justify-content: space-around;
}

.layout-style:hover {
  box-shadow: 5px 5px 5px rgb(170, 166, 166);
}
</style>